<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Работа с аккаунтами</title>
</head>
<body>
<h1>Поиск по ID</h1>
<form id="search_by_id_form">
    <input type="text" id="accountId" placeholder="accountId" required>
    <button type="submit">Поиск</button>
</form>
<h1>Инфо:</h1>
<p id="id"></p>
<p id="firstName"></p>
<p id="lastName"></p>
<p id="email"></p>

<h1>Полный поиск</h1>
<form id="search_form">
    <input type="text" id="firstNameSearch" placeholder="Имя">
    <input type="text" id="lastNameSearch" placeholder="Фамилия">
    <input type="email" id="emailSearch" placeholder="Email">
    <input type="number" id="fromSearch" placeholder="Начиная с">
    <input type="number" id="sizeSearch" placeholder="Размер">
    <button type="submit">Поиск</button>
</form>
<h2>Найденные аккаунты:</h2>
<div id="accountsList"></div>

<h1>Изменить данные</h1>
<form id="editForm">
    <h1 id="succes"></h1>
    <input type="text" id="firstNameEdit" placeholder="Имя" required>
    <input type="text" id="lastNameEdit" placeholder="Фамилия" required>
    <input type="email" id="emailEdit" placeholder="Email" required>
    <input type="password" id="passwordEdit" placeholder="Пароль" required>
    <button type="submit">Изменить</button>
</form>

<h1>Удалить аккаунт</h1>
<form id="deleteAccount">
    <h1 id="successDelete"></h1>
    <button type="submit">Удалить</button>
</form>

<script>

    function getCookie(name) {
        const value = `; ${document.cookie}`;
        const parts = value.split(`; ${name}=`);
        if (parts.length === 2) return parts.pop().split(';').shift();
    }

    const form = document.getElementById('search_by_id_form');

    form.addEventListener('submit', function (event) {
        event.preventDefault();

        const accountId = document.getElementById('accountId').value;

        const params = {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        };

        fetch(`/accounts/${accountId}`, params)
            .then(response => response.json())
            .then(data => {
                if (data.id) {
                    document.getElementById("id").innerText = `ID: ${data.id}`;
                    document.getElementById("firstName").innerText = `First Name: ${data.firstName}`;
                    document.getElementById("lastName").innerText = `Last Name: ${data.lastName}`;
                    document.getElementById("email").innerText = `Email: ${data.email}`;
                } else {
                    document.getElementById("id").innerText = "Not Found";
                }
            })
            .catch((error) => console.error('Ошибка:', error));
    });

    const editForm = document.getElementById('editForm');

    editForm.addEventListener('submit', function (event) {
        event.preventDefault();

        const firstName = document.getElementById('firstNameEdit').value;
        const lastName = document.getElementById('lastNameEdit').value;
        const email = document.getElementById('emailEdit').value;
        const password = document.getElementById('passwordEdit').value;

        const data = JSON.stringify({
            firstName: firstName,
            lastName: lastName,
            email: email,
            password: password
        });

        const params = {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: data
        };

        fetch(`/accounts/${getCookie("id")}`, params)
            .then(response => {
                if (response.status === 200) {
                    document.getElementById("succes").innerText = `Успешное изменение!`;
                    return response.json();
                } else {
                    document.getElementById("succes").innerText = `Ошибка при изменении`;
                }
            })
            .catch((error) => console.error('Ошибка:', error));
    });

    const formDelete = document.getElementById("deleteAccount");

    formDelete.addEventListener('submit', function (event) {
        event.preventDefault();

        const params = {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json'
            }
        };

        fetch(`/accounts/${getCookie("id")}`, params)
            .then(response => {
                if (response.status === 200) {
                    document.getElementById("successDelete").innerText = `Успешное удаление!`;
                    return response.json();
                } else {
                    document.getElementById("successDelete").innerText = `Ошибка при удалении`;
                }
            })
            .catch((error) => console.error('Ошибка:', error));
    });

    const searchForm = document.getElementById('search_form');
    const accountsList = document.getElementById('accountsList');

    searchForm.addEventListener('submit', function (event) {
        event.preventDefault();

        const firstName = document.getElementById('firstNameSearch').value;
        const lastName = document.getElementById('lastNameSearch').value;
        const email = document.getElementById('emailSearch').value;
        const fromParam = document.getElementById('fromSearch').value;
        const size = document.getElementById('sizeSearch').value;

        const params = {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        };

        let url = '/accounts/search?';
        if (firstName) url += `firstName=${firstName}&`;
        if (lastName) url += `lastName=${lastName}&`;
        if (email) url += `email=${email}&`;
        if (fromParam) url += `from=${fromParam}&`;
        if (size) url += `size=${size}`;

        fetch(url, params)
            .then(response => response.json())
            .then(data => {
                accountsList.innerHTML = '';

                data.forEach(account => {
                    const accountDiv = document.createElement('div');
                    console.log(account);
                    accountDiv.innerHTML = `
                        <p>ID: ${account.id}</p>
                        <p>Имя: ${account.firstName}</p>
                        <p>Фамилия: ${account.lastName}</p>
                        <p>Email: ${account.email}</p>
                    `;
                    accountsList.appendChild(accountDiv);
                });
            })
            .catch((error) => console.error('Ошибка:', error));
    });


</script>

</body>
</html>